<template>
  <div ref="containerRef" class="announcement-container">
    <div ref="contentRef" :class="{ scrolling: isScrolling }" :style="scrollStyle" class="scroll-content">
      <span>{{ text }}</span>
      <span v-if="isScrolling">{{ text }}</span>
    </div>
  </div>
</template>

<script setup>
import {computed, onMounted, ref, watch} from 'vue'

const props = defineProps({
  text: {
    type: String,
    required: true,
  },
  scrollSpeed: {
    type: Number,
    default: 30, // 每秒滚动的像素数
  },
  scrollDuration: {
    type: Number,
    default: null, // 若为 null 则根据内容长度动态计算时长
  },
})

const containerRef = ref(null)
const contentRef = ref(null)
const isScrolling = ref(false)

// 动态计算滚动样式
const scrollStyle = computed(() => {
  if (!isScrolling.value) return {}

  const contentWidth = contentRef.value.offsetWidth
  const duration = props.scrollDuration
      ? `${props.scrollDuration}s`
      : `${contentWidth / props.scrollSpeed}s` // 动态计算滚动时长

  return {
    animationDuration: duration,
  }
})

// 检查是否需要滚动
const checkScrolling = async () => {
  await nextTick()
  const containerWidth = containerRef.value.offsetWidth
  const contentWidth = contentRef.value.offsetWidth
  isScrolling.value = contentWidth > containerWidth
}

// 监听文本变化
watch(
    () => props.text,
    () => {
      checkScrolling()
    }
)

onMounted(() => {
  checkScrolling()
})
</script>

<style scoped>
.announcement-container {
  position: relative;
  overflow: hidden;
  white-space: nowrap;
  padding: 5px 7px;
  font-size: 1rem;
  border-radius: 5px;
}

.scroll-content {
  display: inline-block;
  white-space: nowrap;
  animation: none;
}

.scroll-content.scrolling {
  animation: scroll-text linear infinite;
}

@keyframes scroll-text {
  0% {
    transform: translateX(0%);
  }
  100% {
    transform: translateX(-100%);
  }
}
</style>
